/**
 * 
 */
package temp;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import temp.casia.isiteam.zrb.hbase.client.ProjectHbaseClient;
import temp.casia.isiteam.zrb.hbase.client.bean.HBProjectInfo;
import temp.casia.isiteam.zrb.hbase.client.bean.ProjectQueryTerm;
import temp.model.information.ProjectInfo;
import temp.model.information.dto.ProjectInfoDto;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.MessageSendService;
import com.hanhai.zrb.api.biz.service.SysDictionaryService;
import com.hanhai.zrb.api.biz.service.UserStatisticDetailService;
import com.hanhai.zrb.model.common.SysDictionary;
import com.hanhai.zrb.model.common.enums.QueryTypeEnum;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.project.UserProjectRef;
import com.hanhai.zrb.model.project.enums.ProjectStatusEnums;
import com.hanhai.zrb.model.project.vo.MyProjectInfoVo;
import com.hanhai.zrb.model.user.UserStatisticDetail;

/**
 * @author tino
 *
 */
//@WebService(endpointInterface = "com.hanhai.zrb.api.client.facade.ProjectInfoQueryFacade", serviceName = "ProjectInfoQueryFacade")
//@Service("projectInfoQueryFacade")
@Deprecated
public class ProjectInfoQueryFacadeImpl implements ProjectInfoQueryFacade{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private ProjectInfoService projectInfoService;
	
	@Resource
	private SysDictionaryService sysDictionaryService;
	
	@Resource
	private CityInfoService cityInfoService;
	
	@Resource
	private UserStatisticDetailService userStatisticDetailService;
	
//	@Resource
//	private ProjectRelationService projectRelationService;
	
	@Resource
	private UserProjectRefService userProjectRefService;
	

	
	@Resource
	private MessageSendService messageSendService;
	
	/** 
	 * @Title: getProVoByAutoId 
	 * @Description: TODO(Hbase-mysql 联合查询) 
	 * @param idO
	 * @return ProjectInfoQueryResult(返回类型 ) 
	 * @throws 
	 */ 
	public ProjectInfoQueryResult getProVoByAutoId(int id){
		ProjectInfoQueryResult result = new ProjectInfoQueryResult();
		ProjectInfoVo projectInfoVo = projectInfoService.getProVoByAutoId(id);
		if( null == projectInfoVo){
			result.setMsg("项目不存在");
			return result;
		}
		result.setSuccess(true);
		result.setProjectInfoVo(projectInfoVo);
		
		return result;
	}
	
	
	
	
	/** 
	 * @Title: getProByAutoId 
	 * @Description: TODO(查询单个项目信息--mysql) 
	 * @param id
	 * @return ProjectInfoQueryResult(返回类型 ) 
	 * @throws 
	 */ 
	public ProjectInfoQueryResult getProByAutoId(int id){
		ProjectInfoQueryResult result = new ProjectInfoQueryResult();
		ProjectInfo projectInfo = projectInfoService.getProByAutoId(id);
		if( null == projectInfo){
			result.setMsg("项目不存在");
			return result;
		}
		result.setSuccess(true);
		result.setProjectInfo(projectInfo);
		
		return result;
	}
	
	/** 
	 * @Title: getProByProjectId 
	 * @Description: TODO(根据项目编号查询数据) 
	 * @param id
	 * @return ProjectInfoQueryResult(返回类型 ) 
	 * @throws 
	 */ 
	public ProjectInfoQueryResult getProByProjectId(String projectId){
		ProjectInfoQueryResult result = new ProjectInfoQueryResult();
		ProjectInfoDto dto = new ProjectInfoDto();
		List<Integer> listStatus = new ArrayList<Integer>();
		listStatus.add(ProjectStatusEnums.DRAF.getCode());
		listStatus.add(ProjectStatusEnums.RELEASE.getCode());
		listStatus.add(ProjectStatusEnums.WITHDRAW.getCode());
		listStatus.add(ProjectStatusEnums.SUBMIT.getCode());
		listStatus.add(ProjectStatusEnums.DEALPROJECT.getCode());
		dto.setProjectStutsInList(listStatus);
		dto.setProjectId(projectId);
		List<ProjectInfoVo> proVoList = projectInfoService.queryByCondition(dto);
		if( null == proVoList){
			result.setMsg("项目不存在");
			result.setSuccess(false);
			return result;
		}
		result.setSuccess(true);
		result.setProVoList(proVoList);
		
		return result;
		
		
	}	
	
	@Deprecated
	public ProjectInfoQueryResult queryProjectApiList(ProjectInfoDto projectInfoDto,int limit,String pushTime){
		ProjectInfoQueryResult result = new ProjectInfoQueryResult();
		projectInfoDto.setQueryType(QueryTypeEnum.API.getType());
		projectInfoDto.setPageSize(limit);
		projectInfoDto.setPageNum(1);
		if(StringUtils.isNotBlank(pushTime)){
			projectInfoDto.setEndTimes(pushTime);
		}
		projectInfoDto.setProjectStatus(ProjectStatusEnums.RELEASE.getCode());
		PageInfo pageInfo = projectInfoService.queryPageByCondition(projectInfoDto);

		List<ProjectInfoVo> list = pageInfo.getList();
		
		batchQueryHBaseProject(list);
		
		result.setProVoList(list);
		result.setSuccess(true);
		return result;
	}
	
	public ProjectInfoQueryResult queryProjectBannerApiList(ProjectInfoDto projectInfoDto,int limit,String tradeDate){
		ProjectInfoQueryResult result = new ProjectInfoQueryResult();
		projectInfoDto = new ProjectInfoDto();
		projectInfoDto.setPageSize(1);
		projectInfoDto.setPageNum(1);
		projectInfoDto.setIsRecommend(1); //是否属于推介项目，0：否，1：是
	//	projectInfoDto.setProjectStatus(1);//项目状态，1：招商中，2：已成交
		PageInfo pageInfo = projectInfoService.queryPageByCondition(projectInfoDto);
		result.setSuccess(true);
		List<ProjectInfoVo> list = pageInfo.getList();
		batchQueryHBaseProject(list);
		result.setProVoList(list);
		return result;
	}
	
	
	//根据项目信息查询数据
	public String queryPageByCondition(ProjectInfoDto projectInfoDto){
		String str="";
		try {
			PageInfo pageInfo = projectInfoService.queryPageByCondition(projectInfoDto);
//			List<ProjectInfoVo> listRet = new ArrayList<ProjectInfoVo>();
//			List<ProjectInfoVo> list = pageInfo.getList();
//			List<ProjectQueryTerm> queryTermList = null;
//			long startMills = System.currentTimeMillis();
//			if(null!=list){
//				queryTermList = new ArrayList<ProjectQueryTerm>();
//				for (ProjectInfoVo pro:list) {
//					System.out.println(pro.getAutoId()+"_"+pro.getProvincePostcode()+"_"+pro.getCityPostcode()+"_"+pro.getCountyPostcode());
//					queryTermList.add(new ProjectQueryTerm(pro.getAutoId(),pro.getProvincePostcode(),pro.getCityPostcode(),pro.getCountyPostcode()));
					//assetType 资产类型
//					pro = projectInfoService.getPurposeAndAssetTypeByAutoId(pro);	
//					listRet.add(pro);	
//				}
//			}
//			
//			ProjectHbaseClient client = new ProjectHbaseClient();
//			List<HBProjectInfo> pList = client.getProjectInfoBasic(queryTermList);
//			client.closeClient();
			
//			System.out.println("*************query service takes seconds:"+(System.currentTimeMillis()-startMills)/1000);
//			pageInfo.setList(pageInfo.getList());
			
			Map<String, Object> map = new HashMap<String, Object>();
//			PageInfo pageInfo = projectInfoQueryResult.getPageInfoProVo();
			map.put("rows", pageInfo.getList()); 
			map.put("total", pageInfo.getTotal());
			str = JSONObject.toJSONString(map);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}



		return str;
		
	}

	@Override
	public String updateStatus(String ids, int status) {
		List idList = new ArrayList();
		Collections.addAll(idList, ids.split(","));
		Map<String, Object> map=new HashMap<String, Object>();
		for (int i = 0; i < idList.size(); i++) {
			try {
				 int id =Integer.valueOf(idList.get(i).toString());
				ProjectInfo pro = new ProjectInfo();
				pro.setAutoId(id);
				pro.setProjectStatus(status);
				if(status == 203){
					pro.setPushTime(new Date());
//					try {
//						UserProjectRefDto userProjectRefDto = new UserProjectRefDto();
//						userProjectRefDto.setProjectId(String.valueOf(id));
//						List<UserProjectRef> listRef = userProjectRefService.queryRefByConditions(userProjectRefDto);
//						//获取当前项目的关注人
//						if(null!=listRef && listRef.size()>0){
//							List<Long> receiverUids = new ArrayList<Long>();
//							for (UserProjectRef u:listRef) {
//								receiverUids.add(Long.valueOf(u.getUserId()));
//							}
//							String content = null;
//							MessageBizType bizType = MessageBizType.proj_prog_change;
//							String bizKey = String.valueOf(id);
//							boolean result = this.messageSendService.createNotifyMessage(receiverUids, content, bizType, bizKey);	
//						}
//					} catch (Exception e) {
//					}
				}
				projectInfoService.updateStatus(pro);
//				if(2==status){//发布资讯同时更新资讯热榜信息
//					HotPoular record = new HotPoular();
//					record.setId(id);
//					record.setDATASTATUS("1");
//					hotPoularService.updateByPrimaryKeySelective(record);
//				}
				map.put("success", true);
				map.put("infoMsg", "更新项目状态成功");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("success", false);
				map.put("infoMsg", "批量更新项目状态失败，请稍后再试");
			}
			
		}
		String str=JSONObject.toJSONString(map);
		
		return str;
	}
	
	public List<ProjectInfoVo> getProjectInfoVoByIdListForCollectionView(List<Long> idList){
		List<ProjectInfoVo> returnList = new ArrayList<ProjectInfoVo>();
		List<Integer> intIdList = new ArrayList<Integer>();
		for(Long id:idList){
			intIdList.add(id.intValue());
		}
		Map<Integer,ProjectInfoVo> map = this.projectInfoService.queryByIdList(intIdList);
		
		Map<Long,Long> countMap = this.userStatisticDetailService.getCollectionCounterMap(idList, UserStatisticDetail.Type.pro_col);
		
		for(Long id:idList){
			ProjectInfoVo tempVo = map.get(id.intValue());
			if(tempVo!=null){
				Long tempCount = countMap.get(id);
				tempVo.setUserCollectionCount(tempCount);
				returnList.add(tempVo);
			}
		}
		return returnList;
	}


	
	public List<SysDictionary> getDicByCode(String parentCode){
		return sysDictionaryService.getItemByParentCode(parentCode);
	}
	
	public List<CityInfo> findAllProvince(){
    	return cityInfoService.findAllProvince();
    }
	
	public List<CityInfo> findChildCity(Integer topId){
		return cityInfoService.findChildCity(topId);
	}
	
	public CityInfo findByCityName(String cityName){
		return cityInfoService.findByCityName(cityName);
	}
	
	public CityInfo findByParentName(String proName,String cityName,String countryName){
		return cityInfoService.findByParentName(proName, cityName, countryName);
	}
	
	public int saveProject(ProjectInfo project){
		return projectInfoService.saveProject(project);
	}
	
	public void updateProject(ProjectInfo project){
		projectInfoService.updateProject(project);
	}
	
	public void associateMember(Integer projectId,List<String> userIds,Integer refType){
		
		userProjectRefService.deleteByProjectId(projectId, refType);
		
		for(String userId :userIds){
			UserProjectRef userProjectRef = new UserProjectRef();
			userProjectRef.setInsertTime(new Date());
			userProjectRef.setProjectId(projectId);
			userProjectRef.setUserId(Integer.valueOf(userId));
			userProjectRef.setRefType(refType);
			userProjectRefService.insertSelective(userProjectRef);
		}
		
//		 if(null!=userIds&&userIds.size()>0){
//				List<Long> receiverUids = new ArrayList<Long>();
//				for(String id:userIds){
//					receiverUids.add(Long.valueOf(id));
//				}
//				String content = null;
//				MessageBizType bizType = MessageBizType.proj_prog_new;
//				messageSendService.createNotifyMessage(receiverUids, content, bizType, String.valueOf(projectId));	
//		}
	}
	
	@Override
	public List<MyProjectInfoVo> queryMyProjectList(Date insertTime,boolean forward,Integer userId,Integer limit) 
			throws IllegalAccessException, InvocationTargetException{
		return projectInfoService.queryMyProjectList(insertTime, forward, userId, limit);
	}
	
	@Override
	public List<ProjectInfoVo> listAll(){
		return projectInfoService.listAll();
		
	}
	
	@Override
	public List<ProjectInfo> getProjectByNameAndStatus(String name,Integer status){
		return projectInfoService.getProjectByNameAndStatus(name, status);
	}

	
	
	@Override
	public List<ProjectInfoVo> getByIdList(List<Integer> list){
		return projectInfoService.getByIdList(list);
	}
	public List<ProjectInfoVo> queryProBannerByHotpointList(List<HotPointVo> list){
        Map<String,Map> map = new HashMap<String,Map>();
		List<ProjectInfoVo> listRet = new ArrayList<ProjectInfoVo>();
		List<Integer> listInt = new ArrayList<Integer>();
		for (HotPointVo hotPointVo : list) {
			//获取jason格式的数据
			 String parmString = hotPointVo.getParam();
			 if(StringUtils.isNotBlank(parmString)){
					 Map<String,String> maps =(Map<String,String>) JSONObject.parse(parmString); 
//					 hotPointVo.setPicUrl(maps.get("picUrl"));
//					 hotPointVo.setProjectId(maps.get("projectId"));
//					 hotPointVo.setShortName(maps.get("shortName"));
					 //根据projectId查询项目信息，并且把picUrl放入到项目中的bigPic中用于APP解析
					 if(StringUtils.isNotBlank(maps.get("projectId"))){
						 listInt.add(Integer.valueOf(maps.get("projectId")));	
						 
							String tempString = "";
							if( maps.containsKey("pic1")){
								tempString =tempString+maps.get("pic1")+"#";
							}
							if( maps.containsKey("pic2")){
								tempString =tempString+maps.get("pic2")+"#";
							}
							if( maps.containsKey("pic3")){
								tempString =tempString+maps.get("pic3");
							}
							maps.put("picUrl", tempString);
						 map.put(maps.get("projectId"), maps);
					 }	 
			 }
		}
		if(listInt.size()>0){
			 List<ProjectInfoVo> listproVo = projectInfoService.getByIdList(listInt);
				int size = listproVo.size();
				for (int i = 0; i < size; i++) {
					ProjectInfoVo pro = listproVo.get(i);
					//assetType 资产类型
					pro = projectInfoService.getPurposeAndAssetTypeByAutoId(pro);	
					if(map.containsKey(pro.getAutoId().toString())){
						pro.setShortName(map.get(pro.getAutoId().toString()).get("shortName").toString());
						pro.setBigPic(map.get(pro.getAutoId().toString()).get("picUrl").toString());
					}
					
					
					listRet.add(pro);	
				}
		}
		
		return listRet;

		
	}




	@Override
	public Integer queryCountByProName(String projectName) {
		// TODO Auto-generated method stub
		return projectInfoService.queryCountByProName(projectName);
	}
	
	private void batchQueryHBaseProject(List<ProjectInfoVo> list){
		if(null!=list&&list.size()>0){
			List<ProjectQueryTerm> termList = new ArrayList<ProjectQueryTerm>();
			for(ProjectInfoVo vo:list){
				termList.add(new ProjectQueryTerm(vo.getAutoId(),vo.getProvincePostcode(),vo.getCityPostcode(),vo.getCountyPostcode()));
			}
			ProjectHbaseClient client = new ProjectHbaseClient();
			List<HBProjectInfo> hbaseProjects = client.getProjectInfoBasic(termList);
			//client.closeClient();
			
			if(null!=hbaseProjects&&hbaseProjects.size()>0){
				for(ProjectInfoVo vo:list){
					for(HBProjectInfo info:hbaseProjects){
						if(info.getMysqlID()==vo.getAutoId()){
							vo.setAssetType(info.getAssetType());
							vo.setPurpose(info.getPurpose());
							break;
						}
					}
				}
			}
		}
	}
	
}
